Working with PUT, PATCH, and DELETE Operations in iOS
Course: iOS App Development
Topic: Working with PUT, PATCH, and DELETE Operations
Course Link: iOS App Development Training
Demo Link: Register for a Free Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to PUT, PATCH, and DELETE Operations
Modern iOS applications frequently communicate with remote servers to create, retrieve, update, and delete information. For example, a shopping app may update a delivery address, a social media app may edit a profile, and a task management app may delete a completed or unwanted task.
These operations are commonly implemented using HTTP methods. The PUT, PATCH, and DELETE methods allow an iOS application to modify server-side resources through REST APIs. In Swift, these requests can be sent using URLSession.
Understanding these methods helps developers build applications that synchronize user actions with backend databases and handle server responses correctly.
2. Learning Objectives
- Understand the purpose of HTTP PUT, PATCH, and DELETE methods.
- Identify the differences between complete and partial resource updates.
- Configure HTTP requests using URLRequest and URLSession.
- Send JSON data to REST APIs using Swift.
- Handle HTTP status codes and server errors.
- Implement secure and reliable API operations in iOS applications.
- Understand asynchronous networking and error handling.
3. Understanding HTTP Methods
HTTP methods describe the action a client wants a server to perform on a resource. In RESTful applications, resources may represent users, products, orders, tasks, messages, or other application data.
| HTTP Method |
Purpose |
Example |
| GET |
Retrieve resource information. |
Fetch a user's profile. |
| POST |
Create a resource or submit data for processing. |
Create a new task. |
| PUT |
Replace a resource or its representation. |
Replace a user's profile data. |
| PATCH |
Modify selected fields of a resource. |
Update only a user's phone number. |
| DELETE |
Request removal of a resource. |
Delete a task. |
The actual behavior of an endpoint depends on the API's documented contract. Developers should always check the backend documentation before implementing an HTTP method.
4. Understanding the PUT Method
4.1 What Is PUT?
The HTTP PUT method is commonly used to create or replace the state of a resource at a specified URL. In many REST APIs, PUT expects the client to submit the complete representation of the resource being updated.
For example, an iOS application may use PUT to update a profile containing a name, email address, phone number, and city.
4.2 Example PUT Request
PUT /api/users/101
Content-Type: application/json
{
"name": "Rahul Sharma",
"email": "[email protected]",
"phone": "9876543210",
"city": "Mumbai"
}
This request asks the server to replace or set the representation of user 101 using the submitted information, according to the API's rules.
4.3 Important Characteristics of PUT
- It is generally used for full resource replacement.
- It is defined as an idempotent HTTP method: repeating the same request should have the same intended effect on the resource.
- It often requires the complete resource representation expected by the API.
- It can create a resource when the endpoint supports creation at the specified URI.
- It may return a status such as 200 OK, 201 Created, or 204 No Content, depending on the server's behavior.
5. Implementing PUT Using Swift and URLSession
URLSession provides APIs for sending HTTP requests asynchronously. The following example demonstrates how to send a JSON PUT request.
import Foundation
struct User: Codable {
let name: String
let email: String
let phone: String
let city: String
}
func updateUser() async throws {
guard let url = URL(
string: "https://api.example.com/users/101"
) else {
throw URLError(.badURL)
}
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue(
"application/json",
forHTTPHeaderField: "Content-Type"
)
request.setValue(
"application/json",
forHTTPHeaderField: "Accept"
)
let user = User(
name: "Rahul Sharma",
email: "[email protected]",
phone: "9876543210",
city: "Mumbai"
)
request.httpBody = try JSONEncoder().encode(user)
let (data, response) = try await URLSession.shared.data(
for: request
)
guard let httpResponse = response as? HTTPURLResponse else {
throw URLError(.badServerResponse)
}
guard (200...299).contains(httpResponse.statusCode) else {
throw NSError(
domain: "APIError",
code: httpResponse.statusCode,
userInfo: [
NSLocalizedDescriptionKey:
"The server rejected the update."
]
)
}
print("User updated successfully.")
print("HTTP status:", httpResponse.statusCode)
if !data.isEmpty {
print(String(data: data, encoding: .utf8) ?? "")
}
}
5.1 Code Explanation
- URL: Identifies the user resource on the server.
- URLRequest: Stores the request configuration.
- httpMethod: Sets the method to PUT.
- Content-Type: Indicates that the request body contains JSON.
- JSONEncoder: Converts the Swift User model into JSON data.
- URLSession.shared.data(for:): Sends the request asynchronously.
- HTTPURLResponse: Provides the server's HTTP status code.
- Status validation: Checks whether the server returned a successful response.
Important: The example API URL is a placeholder. Replace it with your actual backend endpoint and adapt the User model to match the server's expected fields. If the API returns 204 No Content, the response body may be empty; the code accounts for this.
6. Understanding the PATCH Method
6.1 What Is PATCH?
The HTTP PATCH method is used to apply partial modifications to an existing resource. Instead of submitting the complete resource, the client sends the fields or operations that need to change.
For example, if a user wants to update only their city, the application may send a PATCH request containing just the city field.
6.2 Example PATCH Request
PATCH /api/users/101
Content-Type: application/json
{
"city": "Pune"
}
In this example, the request asks the server to change the user's city. Other profile fields should remain unchanged if that is how the endpoint defines the operation.
6.3 Important Characteristics of PATCH
- It is designed for partial resource modification.
- It can reduce the amount of data transferred over the network.
- It is useful when editing individual profile fields, preferences, or task properties.
- Its request format depends on the API. Some endpoints accept ordinary JSON, while others use formats such as JSON Merge Patch or JSON Patch.
- Unlike PUT, PATCH is not guaranteed to be idempotent in every implementation. The behavior depends on the patch operation and API design.
7. Implementing PATCH Using Swift and URLSession
The following example updates only the city field of a user profile.
import Foundation
struct CityUpdate: Encodable {
let city: String
}
func updateUserCity() async throws {
guard let url = URL(
string: "https://api.example.com/users/101"
) else {
throw URLError(.badURL)
}
var request = URLRequest(url: url)
request.httpMethod = "PATCH"
request.setValue(
"application/json",
forHTTPHeaderField: "Content-Type"
)
request.setValue(
"application/json",
forHTTPHeaderField: "Accept"
)
let update = CityUpdate(city: "Pune")
request.httpBody = try JSONEncoder().encode(update)
let (_, response) = try await URLSession.shared.data(
for: request
)
guard let httpResponse = response as? HTTPURLResponse else {
throw URLError(.badServerResponse)
}
guard (200...299).contains(httpResponse.statusCode) else {
throw NSError(
domain: "APIError",
code: httpResponse.statusCode,
userInfo: [
NSLocalizedDescriptionKey:
"Unable to update the user's city."
]
)
}
print("City updated successfully.")
}
7.1 Why Is PATCH Useful?
Suppose a user profile contains ten fields but the user changes only one field. Sending all ten fields may be unnecessary. PATCH can transmit only the intended modification, provided the API supports that request format.
This approach can simplify edit screens, reduce accidental overwriting of unrelated fields, and make update requests more efficient.
8. Understanding the DELETE Method
8.1 What Is DELETE?
The HTTP DELETE method requests the removal of a resource identified by a URL. In an iOS application, it can be used to delete saved addresses, remove tasks, cancel certain records, or delete a user-created item.
8.2 Example DELETE Request
DELETE /api/tasks/501
Accept: application/json
This request asks the server to delete task 501. Whether the data is physically deleted, soft-deleted, or retained for auditing depends on the backend implementation.
8.3 Important Characteristics of DELETE
- It requests removal of the target resource.
- It is defined as idempotent with respect to its intended effect, although repeated requests may return different status codes.
- It commonly returns 200 OK, 202 Accepted, or 204 No Content.
- Some APIs return 404 Not Found if the resource has already been deleted or does not exist.
- Authentication, authorization, and server-side validation may be required.
9. Implementing DELETE Using Swift and URLSession
The following function sends a DELETE request to remove a task from a backend service.
import Foundation
func deleteTask() async throws {
guard let url = URL(
string: "https://api.example.com/tasks/501"
) else {
throw URLError(.badURL)
}
var request = URLRequest(url: url)
request.httpMethod = "DELETE"
request.setValue(
"application/json",
forHTTPHeaderField: "Accept"
)
let (_, response) = try await URLSession.shared.data(
for: request
)
guard let httpResponse = response as? HTTPURLResponse else {
throw URLError(.badServerResponse)
}
guard (200...299).contains(httpResponse.statusCode) else {
throw NSError(
domain: "APIError",
code: httpResponse.statusCode,
userInfo: [
NSLocalizedDescriptionKey:
"Unable to delete the task."
]
)
}
print("Task deleted successfully.")
}
9.1 How the DELETE Code Works
- Creates a URL for the task that must be deleted.
- Creates a URLRequest and sets its method to DELETE.
- Sends the request using URLSession.
- Converts the response into HTTPURLResponse.
- Checks whether the returned status code indicates success.
- Reports success only after receiving a successful HTTP response.
For a real application, show an appropriate confirmation or updated interface after success. Do not remove important local data permanently before confirming the server operation unless the application deliberately supports optimistic updates and rollback.
10. Comparing PUT, PATCH, and DELETE
| Feature |
PUT |
PATCH |
DELETE |
| Main purpose |
Replace or set a resource representation. |
Apply partial changes. |
Request resource removal. |
| Request body |
Often contains the complete representation. |
Contains the changes or patch instructions. |
Often unnecessary, but API-specific. |
| Typical use case |
Replace profile details. |
Change one profile field. |
Remove a saved task. |
| Idempotent |
Yes, by HTTP semantics. |
Not guaranteed. |
Yes, by HTTP semantics. |
| Common success response |
200, 201, or 204. |
200 or 204. |
200, 202, or 204. |
11. Handling HTTP Status Codes
HTTP status codes help an iOS application determine what happened after sending a request. The application should interpret them according to the API's documentation.
| Status Code |
Meaning |
Recommended Handling |
| 200 OK |
Request succeeded. |
Process the response body if provided. |
| 201 Created |
A resource was created. |
Update the application state with the returned resource when applicable. |
| 202 Accepted |
Request accepted for processing. |
Show pending status if the operation is asynchronous. |
| 204 No Content |
Request succeeded without a response body. |
Do not attempt to decode a required JSON body. |
| 400 Bad Request |
Invalid request or input. |
Validate data and display a useful message. |
| 401 Unauthorized |
Authentication is missing or invalid. |
Refresh credentials or request sign-in when appropriate. |
| 403 Forbidden |
Access is not permitted. |
Explain that the operation is not allowed. |
| 404 Not Found |
Resource or endpoint was not found. |
Refresh stale data or inform the user. |
| 409 Conflict |
Request conflicts with the current resource state. |
Resolve conflicts or reload the resource. |
| 422 Unprocessable Content |
Submitted content failed application validation. |
Show field-specific validation errors when available. |
| 429 Too Many Requests |
Rate limit exceeded. |
Respect Retry-After if provided. |
| 500 Internal Server Error |
Server encountered an error. |
Show a generic message and retry only when appropriate. |
12. Error Handling in iOS Networking
Network requests can fail for several reasons, including unavailable internet connectivity, DNS problems, timeouts, invalid JSON, expired credentials, and backend errors. A robust iOS application should distinguish transport errors from HTTP errors.
12.1 Common Error Categories
- URL errors: Invalid URLs, connection failures, or timeouts.
- HTTP errors: The server responds with a non-success status code.
- Encoding errors: Swift data cannot be converted to the expected request format.
- Decoding errors: The response does not match the expected Swift model.
- Authentication errors: Credentials or access tokens are invalid or expired.
12.2 Example Error Handling
func performUpdate() async {
do {
try await updateUser()
print("Update completed.")
} catch let error as URLError {
print("Network error:", error.localizedDescription)
} catch {
print("Request failed:", error.localizedDescription)
}
}
This example handles errors from the update function. In a production application, errors should be converted into meaningful application states rather than only printed to the console.
13. Adding Authentication Headers
Many APIs require an access token before allowing users to update or delete data. A bearer token can be supplied through the Authorization header when required by the API.
request.setValue(
"Bearer YOUR_ACCESS_TOKEN",
forHTTPHeaderField: "Authorization"
)
Replace the placeholder with a valid token obtained through the application's authentication flow. Never hardcode production credentials or commit secrets to source control. Store sensitive tokens using appropriate secure storage, such as Keychain, and avoid logging them.
14. Updating the User Interface After an API Request
After a successful update or deletion, the iOS interface should reflect the new server state. For example, a profile screen may show the updated city, while a task list may remove a deleted task.
When updating SwiftUI state, ensure UI-related changes occur on the main actor. One approach is to isolate the UI update in a MainActor-isolated method.
import SwiftUI
@MainActor
final class TaskViewModel: ObservableObject {
@Published var message = ""
@Published var isLoading = false
func removeTask() async {
isLoading = true
defer { isLoading = false }
do {
try await deleteTask()
message = "Task deleted successfully."
} catch {
message = "Unable to delete task. Please try again."
}
}
}
This is a simplified example of managing loading and feedback states. A complete implementation should also update the task collection, handle cancellation, and use a dedicated service layer when appropriate.
15. Best Practices for PUT, PATCH, and DELETE
- Read the API documentation to understand the exact endpoint behavior and payload format.
- Use PUT when the API expects a replacement representation and PATCH when it supports partial modification.
- Validate input before sending requests to reduce avoidable server errors.
- Set appropriate Content-Type and Accept headers.
- Check HTTPURLResponse status codes instead of assuming every completed URLSession request succeeded.
- Handle 204 No Content without attempting to decode a nonexistent response body.
- Use authentication and authorization securely.
- Show confirmation before destructive operations when appropriate.
- Prevent accidental duplicate user actions while a request is in progress.
- Retry requests carefully. Idempotency does not mean every retry is harmless for every application workflow.
- Respect server rate limits and retry guidance.
- Use HTTPS to protect data in transit.
- Test success responses, error responses, slow connections, and offline behavior.
- Keep networking logic separate from view code to improve maintainability and testing.
16. Common Mistakes and Troubleshooting
| Problem |
Possible Cause |
Solution |
| 405 Method Not Allowed |
The endpoint does not support the selected method. |
Check the API documentation and endpoint configuration. |
| 415 Unsupported Media Type |
The server does not accept the submitted content format. |
Use the required Content-Type header and payload format. |
| 400 Bad Request |
Missing fields or invalid JSON. |
Inspect the request body and validation rules. |
| 401 Unauthorized |
Missing, expired, or invalid token. |
Use the correct authentication flow. |
| Data unexpectedly disappears |
A partial update was interpreted incorrectly or a PUT replaced omitted fields. |
Verify the API contract and request payload. |
| JSON decoding fails |
The response structure differs from the Swift model. |
Check the response schema and handle empty responses. |
| UI does not refresh |
Local state was not updated after success. |
Update the observable model or reload the resource. |
| Repeated deletion errors |
The resource may already have been deleted. |
Handle the documented missing-resource behavior. |
17. Practical Example: Managing a User Profile
Consider an iOS application that allows users to edit their profile. The app communicates with a REST API to save changes.
Scenario A: Replacing Profile Information
The user edits their name, email, phone number, and city. The app sends a PUT request with the complete representation expected by the API.
Scenario B: Updating One Field
The user changes only their phone number. If the API supports partial updates, the app sends a PATCH request containing the new phone number.
Scenario C: Removing a Saved Address
The user confirms the removal of an address. The app sends a DELETE request to the address endpoint, checks the server response, and updates the local interface.
Suggested Workflow
- Collect the user's input.
- Validate the information locally.
- Build the appropriate URLRequest.
- Encode the request body when needed.
- Send the request using URLSession.
- Check the HTTP status code.
- Update the local application state after success.
- Show clear feedback when the operation fails.
18. Testing PUT, PATCH, and DELETE Requests
Testing helps verify that the app sends correct requests and handles different server responses reliably.
- Test PUT with complete and invalid resource representations.
- Test PATCH with one field, multiple fields, and invalid patch data.
- Test DELETE with an existing resource and a resource that no longer exists.
- Verify the HTTP method, endpoint, headers, and request body.
- Test successful responses such as 200 and 204.
- Test authentication failures, permission errors, and server failures.
- Simulate slow networks, offline conditions, and request timeouts.
- Confirm that the interface displays correct loading, success, and failure states.
Developers can use a mock URLProtocol, a dedicated test server, or a suitable API testing tool to verify request construction without relying on production data.
19. Practice Exercises
- Create a Swift function that updates all supported fields of a product using PUT.
- Implement PATCH to update only the description of a product.
- Create a DELETE request to remove a saved item from a user's list.
- Add an Authorization header to an update request.
- Handle 204 No Content without decoding JSON.
- Display an error message when the server returns 401 or 403.
- Create a SwiftUI button that calls a delete function asynchronously.
- Write unit tests for successful and unsuccessful HTTP responses.
20. Interview Questions and Answers
Q1. What is the main difference between PUT and PATCH?
Answer: PUT is commonly used to replace a resource representation, while PATCH applies partial modifications. The exact behavior depends on the API contract.
Q2. What is the purpose of the DELETE method?
Answer: DELETE requests removal of a resource identified by a URL.
Q3. How do you send a PUT request in Swift?
Answer: Create a URLRequest, set its httpMethod to PUT, encode the payload if needed, and send it with URLSession.
Q4. Is PATCH always idempotent?
Answer: No. PATCH is not guaranteed to be idempotent. Its behavior depends on the patch format and operation.
Q5. What does HTTP 204 mean?
Answer: The request succeeded, but the server does not return a response body.
Q6. Why should developers check HTTP status codes?
Answer: URLSession can complete a network request even when the server returns an HTTP error. Checking the status code allows the application to distinguish successful responses from rejected requests.
Q7. Why might a PUT request overwrite existing fields?
Answer: The endpoint may treat PUT as complete resource replacement, so omitted fields may be reset, removed, or handled according to server-specific rules.
Q8. How can an iOS app securely authenticate an API request?
Answer: Use the application's supported authentication flow, transmit requests over HTTPS, attach valid credentials securely, and protect tokens using appropriate secure storage.
Q9. How should a DELETE operation update the interface?
Answer: After a successful response, update the local data model and refresh the interface. If the request fails, preserve or restore the appropriate state and show a useful message.
Q10. What is URLSession used for?
Answer: URLSession provides APIs for network communication, including sending HTTP requests and receiving response data asynchronously.
21. Quick Revision
- PUT: Replaces or sets a resource representation according to the API contract.
- PATCH: Applies partial changes to a resource.
- DELETE: Requests removal of a resource.
- URLRequest: Configures the HTTP method, headers, and request body.
- URLSession: Sends the request and receives the response.
- JSONEncoder: Converts Encodable Swift values into JSON data.
- HTTPURLResponse: Exposes the HTTP status code and response headers.
- Error handling: Separates transport failures from HTTP failures.
- Security: Use HTTPS, secure authentication, and appropriate authorization checks.
- UI updates: Reflect successful server operations in the app's local state.
22. Conclusion
PUT, PATCH, and DELETE are essential HTTP methods for building interactive iOS applications that communicate with REST APIs. PUT is commonly used to replace a resource representation, PATCH supports partial modifications, and DELETE requests resource removal.
By combining URLRequest, URLSession, JSON encoding, HTTP status validation, secure authentication, and reliable error handling, iOS developers can build applications that manage server-side data efficiently. Practical exercises and testing help reinforce these concepts and prepare developers to implement real-world networking features.
23. Learn More with JustAcademy
Explore iOS app development concepts, practical projects, and networking fundamentals through the following resources.